package com.ruoyi.servie.service.impl;

import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.ruoyi.common.core.domain.ResultResponse;
import com.ruoyi.servie.param.SubscribeMsgParam;
import com.ruoyi.servie.service.IWeChatAppletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class WeChatAppletServiceImpl implements IWeChatAppletService {

    @Autowired
    private WxMaDefaultConfigImpl wxConfig;

    @Override
    public ResultResponse sendSubscribeMsg(SubscribeMsgParam subscribeMsgParam) {

        // 1.配置小程序信息
        WxMaServiceImpl wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(wxConfig);

        // 2.设置模板信息
        Map<String, String> subscribeData = subscribeMsgParam.getSubscribeData();
        List<WxMaSubscribeMessage.Data> wxMaSubscribeMessageData = new ArrayList();
        subscribeData.forEach((key, value)->{
            WxMaSubscribeMessage.Data data = new WxMaSubscribeMessage.Data();
            data.setName(key);
            data.setValue(value);
            wxMaSubscribeMessageData.add(data);
        });

        // 3.设置模板消息
        WxMaSubscribeMessage wxMaSubscribeMessage = WxMaSubscribeMessage.builder()
                .toUser(subscribeMsgParam.getOpenid())
                .templateId(subscribeMsgParam.getTemplateId())
                .page(subscribeMsgParam.getPage())
                .data(wxMaSubscribeMessageData)
                .build();

        // 4.推送消息
        ResultResponse response = new ResultResponse();
        try {
            wxMaService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
        } catch (Exception e) {
            response.setShuCode("error");
            response.setMsg(e.toString());
        }
        return response;
    }
}
